package com.gitee.yannzh.rune.core.base.pagination;

import lombok.Data;

import java.io.Serializable;
import java.util.Collections;
import java.util.List;
import java.util.function.Function;

import static java.util.stream.Collectors.toList;


/**
 * 分页
 *
 * @author yann
 */
@Data
public class PageResult<T> implements Serializable {
    private static final long serialVersionUID = 1L;

    protected List<T> records = Collections.emptyList();

    protected long total;
    /**
     * 每页显示条数，默认 10
     */
    protected long size = 10L;

    /**
     * 当前页
     */
    protected long current;


    public long getPages() {
        if (getSize() == 0) {
            return 0L;
        }
        long pages = getTotal() / getSize();
        if (getTotal() % getSize() != 0) {
            pages++;
        }
        return pages;
    }


    public static <T> PageResult<T> of(List<T> data, long total, long size, long current) {
        PageResult<T> result = of(data, total, size);
        result.setCurrent(current);
        return result;
    }

    public static <T> PageResult<T> of(List<T> data, long total, long size) {
        PageResult<T> result = new PageResult<T>();
        result.setRecords(data);
        result.setTotal(total);
        result.setSize(size);
        return result;
    }

    @SuppressWarnings("unchecked")
    public <R> PageResult<R> convert(Function<? super T, ? extends R> mapper) {
        List<R> collect = this.getRecords().stream().map(mapper).collect(toList());
        ((PageResult<R>) this).setRecords(collect);
        return (PageResult<R>) this;
    }

}